package com.security.manage.search.util;

import com.alibaba.nacos.api.config.annotation.NacosProperty;
import com.security.manage.search.model.FileModel;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
@RefreshScope
public class FastDfsClient {

    private StorageClient storageClient;
    private String url="";

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${fastdfs.ip}")
    private String ip;
    @Value("${fastdfs.port}")
    private Integer port;

    @PostConstruct
    public void init(){
        try {
            logger.error("fastdfs::"+ip+":"+port);
            ClientGlobal.initByTrackers(ip+":"+port);
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getTrackerServer();
            url = "http://"+trackerServer.getInetSocketAddress().getHostString()+":"+ ClientGlobal.getG_tracker_http_port()+"/";
            storageClient = new StorageClient(trackerServer, null);
        }catch (Exception e){
        }

    }

    public String uploadFile(FileModel file) throws IOException, MyException {
        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("author", file.getAuthor());
        String[] uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
        String groupName = uploadResults[0];
        String remoteFileName = uploadResults[1];
        return url+groupName+"/"+remoteFileName;
    }
    /**
     * 查询文件信息
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public FileInfo getFile(String groupName, String remoteFileName) {
        try {
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (IOException e) {
            logger.error("IO Exception: Get File from Fast DFS failed", e);
        } catch (Exception e) {
            logger.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }

    /**
     * 下载文件
     * @param groupName 文件路径
     * @param remoteFileName 输出流 中包含要输出到磁盘的路径
     * @return
     */
    public InputStream downFile(String groupName, String remoteFileName) {
        try {
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            InputStream ins = new ByteArrayInputStream(fileByte);
            return ins;
        } catch (IOException e) {
            logger.error("IO Exception: Get File from Fast DFS failed", e);
        } catch (Exception e) {
            logger.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }

    /**
     * 删除文件
     * ==0表示成功
     * @param groupName 组名 如：group1
     * @param remoteFileName 不带组名的路径名称 如：M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @throws Exception
     */
    public int deleteFile(String groupName, String remoteFileName)
            throws Exception {
        return storageClient.delete_file(groupName, remoteFileName);
    }

}
